using DynamicAuthorization.Sdk.Abstarctions;
using Microsoft.AspNetCore.Http;
using System.Reflection;

namespace DynamicAuthorization.Sdk.Impl;

internal class GrantValidator : IGrantValidator
{
    private readonly IUserGrantHandler _handler;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IGrantService _service;

    public GrantValidator(IUserGrantHandler handler, IGrantService service, IHttpContextAccessor httpContextAccessor)
    {
        _handler = handler;
        _service = service;
        _httpContextAccessor = httpContextAccessor;
    }

    public async Task<bool> CheckAsync(string username, Type controller, MethodInfo action, CancellationToken cancellationToken = default)
    {
        var context = _httpContextAccessor.HttpContext;

        if (context is null)
        {
            throw new NotSupportedException("仅支持基于HTTP协议的Web请求访问");
        }

        var grant = await _handler.GetUserGrantsAsync(username, cancellationToken);

        return grant is null
            ? throw new ArgumentException($"用户{username}不存在", nameof(username))
            : _service.Check(grant, controller, action);
    }
}